//
//  HHConversationViewController.m
//  HHChatKit
//
//  Created by Henry on 2021/5/10.
//

#import "HHConversationViewController.h"
#import "HHConversationNoNetCell.h"
#import "HHNavBarIndicatorView.h"
#import "HHChatConfiguration.h"
#import "HHResources.h"
#import "HHChatHelper.h"

@interface HHConversationViewController ()

@property (nonatomic, strong) HHNavBarIndicatorView *titleView;
@property (nonatomic, strong) UIButton *addButton;

@end

@implementation HHConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [HHChatConfiguration shareInstance].backgroundColor;
    [self initView];
}

- (void)initView {
    [self.view addSubview:self.tableView];
    [HHConversationCell registerCellToTableView:self.tableView];
    [HHConversationNoNetCell registerCellToTableView:self.tableView];
}

- (void)setupNavigation {
    _titleView = [[HHNavBarIndicatorView alloc] init];
    [_titleView setTitle:@"交流"];
    self.navigationItem.titleView = _titleView;
    self.navigationItem.title = @"";
}

- (void)setupRightItem {
    UIImage *image = [HHResources getImageFromMessage:@"conversation_add"];
    self.addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.addButton.frame = CGRectMake(0, 0, 50, 50);
    [self.addButton setImage:image forState:UIControlStateNormal];
    [self.addButton addTarget:self action:@selector(onClickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.addButton];
}

- (void)onClickRightItem:(UIButton *)sender {

}

#pragma mark - Public

- (void)setNavTitle:(NSString *)title {
    [self setNavTitle:title animating:NO];
}

- (void)setNavTitle:(NSString *)title animating:(BOOL)animating {
    [_titleView setTitle:title];
    if (animating) {
        [_titleView startAnimating];
    } else {
        [_titleView stopAnimating];
    }
}

- (void)addNoNet {
    HHConversationModel *conv = [[HHConversationModel alloc] initWithType:HHConversationTypeNoNet];
    [self.dataArray insertObject:conv atIndex:0];
    [self.tableView reloadData];
}

- (void)removeNoNet {
    for (HHConversationModel *conv in self.dataArray) {
        if (conv.convType == HHConversationTypeNoNet) {
            [self.dataArray removeObject:conv];
            break;
        }
    }
    [self.tableView reloadData];
}

- (NSArray *)sortDataList:(NSMutableArray<HHConversationModel *> *)dataList {
    // 按时间排序，最近会话在上
    [dataList sortUsingComparator:^NSComparisonResult(HHConversationModel *obj1, HHConversationModel *obj2) {
        return [obj2.time compare:obj1.time];
    }];
    
    // 将置顶会话固定在最上面
    NSMutableArray *topIdxArr = [NSMutableArray array];
    for (int i = 0; i < dataList.count; i++) {
        if (dataList[i].top) {
            [topIdxArr addObject:@(i)];
        }
    }
    
    int existTopListSize = 0;
    for (int j = 0; j < topIdxArr.count; j ++) {
        NSInteger userIdx = [topIdxArr[j] integerValue];
        HHConversationModel *data = dataList[userIdx];
        [dataList removeObjectAtIndex:userIdx];
        [dataList insertObject:data atIndex:existTopListSize];
        existTopListSize++;
    }
    return dataList;
}

- (void)removeIndexPath:(NSIndexPath *)indexPath {
    HHConversationModel *model = self.dataArray[indexPath.row];
    // 删除会话本地
    [HHChatHelper removeConv:model.identifier];
    [self.dataArray removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HHConversationModel *conv = self.dataArray[indexPath.row];
    if (conv.convType == HHConversationTypeNoNet) {
        HHConversationNoNetCell *cell = [HHConversationNoNetCell dequeueOrCreateCellByTableView:tableView];
        cell.model = conv;
        return cell;
    }

    HHConversationCell *cell = [HHConversationCell dequeueOrCreateCellByTableView:tableView];
    cell.model = conv;
    
    if (_delegate && [_delegate respondsToSelector:@selector(conversationConfigCell:indexPath:)]) {
        [_delegate conversationConfigCell:cell indexPath:indexPath];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HHConversationModel *conv = self.dataArray[indexPath.row];
    if (conv.convType == HHConversationTypeNoNet) {
        return [HHConversationNoNetCell viewHeight:conv];
    }
    return [HHConversationCell viewHeight:conv];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HHConversationModel *conv = self.dataArray[indexPath.row];
    if (conv.convType == HHConversationTypeNoNet) {
        if (_delegate && [_delegate respondsToSelector:@selector(conversationDidSelectNoNet)]) {
            [_delegate conversationDidSelectNoNet];
        }
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(conversationDidSelectRow:indexPath:)]) {
        [_delegate conversationDidSelectRow:conv indexPath:indexPath];
    }
}

#pragma mark - Getters

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        tableView.tableFooterView = [[UIView alloc] init];
        
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        
        tableView.backgroundColor = self.view.backgroundColor;
        
        _tableView = tableView;
    }
    return _tableView;
}

@end
